#include "stdafx.h"
#include "StormLib.h"
#include "PakFile.h"


initialiseSingleton(CPakFile);

CPakFile::CPakFile(void)
{
    CString str = ModulePath();
    CreateArchive(str+_T("config\\data.dat"),OPEN_ALWAYS);
}

CPakFile::~CPakFile(void)
{
    CloseArchive();
}

BOOL CPakFile::CreateArchive(const char*file, DWORD dwCreationDisposition)
{
    if (OPEN_EXISTING==dwCreationDisposition)
        return SFileOpenArchive(file, dwCreationDisposition, 200, &mhPak);
    return SFileCreateArchiveEx(file, dwCreationDisposition, 200, &mhPak);
}

BOOL CPakFile::CreateArchive(LPCTSTR lpszFile, DWORD dwCreationDisposition)
{
    char lpAnsi[256] = {0};
    ::WideCharToMultiByte(CP_ACP, 0, lpszFile, lstrlen(lpszFile)+1, lpAnsi, 2*(1+lstrlen(lpszFile)), NULL, NULL);
    return CreateArchive(lpAnsi, dwCreationDisposition);
}

BOOL CPakFile::CloseArchive()
{
    return SFileCloseArchive(mhPak);
}

BOOL CPakFile::HasFile(LPCTSTR lpszFile)
{
    char lpAnsi[256] = {0};
    ::WideCharToMultiByte(CP_ACP, 0, lpszFile, lstrlen(lpszFile)+1, lpAnsi, 2*(lstrlen(lpszFile)+1), NULL, NULL);
    return SFileHasFile(mhPak, lpAnsi);
}

BOOL CPakFile::OpenFile(const char*file, HANDLE* phFile)
{
    return SFileOpenFileEx(mhPak, file, SFILE_OPEN_FROM_MPQ, phFile);
}

BOOL CPakFile::OpenFile(LPCTSTR lpszFile, HANDLE* phFile)
{
    char lpAnsi[256] = {0};
    ::WideCharToMultiByte(CP_ACP, 0, lpszFile, lstrlen(lpszFile)+1, lpAnsi, 2*(1+lstrlen(lpszFile)), NULL, NULL);
    return OpenFile(lpAnsi, phFile);
}

BOOL CPakFile::CloseFile(HANDLE hFile)
{
    return SFileCloseFile(hFile);
}

// File I/O
DWORD CPakFile::GetFilePos(HANDLE hFile, DWORD * pdwFilePosHigh)
{
    return SFileGetFilePos(hFile, pdwFilePosHigh);
}

DWORD CPakFile::GetFileSize(HANDLE hFile, DWORD * pdwFileSizeHigh)
{
    return SFileGetFileSize(hFile, pdwFileSizeHigh);
}

DWORD CPakFile::SetFilePointer(HANDLE hFile, LONG lFilePos, LONG * pdwFilePosHigh, DWORD dwMethod)
{
    return SFileSetFilePointer(hFile, lFilePos, pdwFilePosHigh, dwMethod);
}

BOOL  CPakFile::ReadFile(HANDLE hFile, VOID * lpBuffer, DWORD dwToRead, DWORD * pdwRead)
{
    return SFileReadFile(hFile, lpBuffer, dwToRead, pdwRead);
}

BOOL CPakFile::WriteBuffFile(const char*szBuf, DWORD dwSize, const char * szArchivedName, DWORD dwFlags)
{
    return SFileAddFileByBuff(mhPak, szBuf, dwSize, szArchivedName, MPQ_FILE_REPLACEEXISTING);
}

